package com.asialjim.wechat.official.controller;

import com.asialjim.wechat.apiservice.enumeration.WeChatApiReturnEnumeration;
import com.asialjim.wechat.apiservice.exception.WeChatApiException;
import com.asialjim.wechat.database.DataBaseService;
import com.asialjim.wechat.official.apiservice.OfficialMenuService;
import com.asialjim.wechat.official.menu.OfficialMenu;
import com.asialjim.wechat.pojo.account.WeChatAccount;
import com.asialjim.wechat.pojo.account.WeChatAccountHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Objects;

/**
 * <h1><em>ASIAL JIM JAVA DOC</em></h1><hr/>
 * <h2>CLASS DESCRIPTION <i>[ NAME: OfficialMenuController ]</i></h2><strong>
 * <p> official menu controller
 * </strong><p><p><em>Copyright &copy; Asial Jim Co., LTD</em><hr/>
 *
 * @author Asial Jim &nbsp;&nbsp; <span>Email:<a href="mailto:asialjim@hotmail.com">asialjim@hotmail.com</a> &nbsp;&nbsp; <a href="asialjim@qq.com">asialjim@qq.com</a></span>
 * @version 1.0.0
 * @since 2021/3/18   &nbsp;&nbsp; JDK 8
 */
@Data
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/menu")
@Api("official menu service")
public class OfficialMenuController {
    private final OfficialMenuService menuService;
    private final DataBaseService dataBaseService;

    @PostMapping
    @ApiOperation("save official menu service")
    public List<OfficialMenu> save(String appId, @RequestBody List<OfficialMenu> menus){
        weChatAccount(appId);
        return menuService.addAll(menus);
    }

    @PostMapping("/save")
    @ApiOperation("save one menu service")
    public List<OfficialMenu> saveOne(String appId,@RequestBody OfficialMenu menu){
        weChatAccount(appId);
        return menuService.add(menu);
    }

    @GetMapping("/create")
    public void createSelfMenu(String toUserName){
        if (StringUtils.isBlank(toUserName)){
            WeChatApiException.cast(WeChatApiReturnEnumeration.CODE_40086);
        }
        WeChatAccount weChatAccount = dataBaseService.selectOne(WeChatAccount.builder().subjectId(toUserName).build());
        if (Objects.nonNull(weChatAccount)){
            WeChatAccountHolder.set(weChatAccount);
        }
        menuService.create();
    }

    private void weChatAccount(String appId) {
        WeChatAccount weChatAccount = dataBaseService.selectOne(WeChatAccount.builder().appId(appId).build());
        if (Objects.nonNull(weChatAccount)) {
            WeChatAccountHolder.set(weChatAccount);
        } else {
            // todo throw an exception
        }
    }
}
